package com.controller;

import com.entity.RbacManager;
import com.entity.ResponseEntity;
import com.service.RbacManagerService;
import com.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    private RbacManagerService rbacManagerService;
    private RedisTemplate redisTemplate;
    @Autowired
    public void setRbacManagerService(RbacManagerService rbacManagerService) {
        this.rbacManagerService = rbacManagerService;
    }
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/login")
    @CrossOrigin
    public ResponseEntity login(String username,String password){
        RbacManager rbacManager = rbacManagerService.login(username, password);
        if (!StringUtils.isEmpty(rbacManager)){
            //就说明查出了用户数据
            String token =  JWTUtils.sign(username, password);
            /**
             * 将带有token的对象放入redis
             */
            rbacManager.setToken(token);
            redisTemplate.opsForValue().set("loginUser",rbacManager);

//            redisTemplate.expire("loginUser",50*60*1000, TimeUnit.SECONDS);
            return new ResponseEntity<>(200,"登录成功",null);
        }else {
            return ResponseEntity.FAIL;
        }
    }

    @RequestMapping("/401")
    public ResponseEntity response401(){
        return new ResponseEntity(401,"认证异常",null);
    }
}
